#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: __init__.py.py
@time: 2020/7/17 3:43 下午
@desc:
'''

import time
from peewee import ModelUpdate,ModelInsert,CharField,IntegerField,TimestampField
from playhouse.signals import Model, post_save
from . import DBUtil
from core.db import database

class BaseModel(Model,DBUtil):

    show_id = CharField(max_length=32, verbose_name='展示ID', help_text="展示ID",default='')
    add_time = TimestampField(verbose_name='添加时间',help_text='添加时间',index=True,default=0)
    upd_time = TimestampField(verbose_name='更新时间',help_text='更新时间',default=0)
    delete_time = TimestampField(verbose_name='删除', help_text='删除', default=0,index=True)

    class Meta:
        database=database

    @classmethod
    def insert(cls, __data=None, **insert):
        insert.update({
                'add_time':time.time(),
                'upd_time':time.time()
        })
        return ModelInsert(cls, cls._normalize_data(__data, insert))
    @classmethod
    def update(cls, __data=None, **update):
        update.update({'upd_time':time.time()})
        return ModelUpdate(cls, cls._normalize_data(__data, update))
    @classmethod
    def insert_many(cls, rows, fields=None):
        for row in rows:
            row.update({
                    'add_time': time.time(),
                    'upd_time': time.time()
            })
        return ModelInsert(cls, insert=rows, columns=fields)


@post_save(sender=BaseModel)
def on_save_handler(model_class, instance, created):
    '''
    自动填充show_id
    自动发更新时间
    :param model_class:
    :param instance:
    :param created:
    :return:
    '''
    kargs = {}
    if not instance.show_id:
        kargs.update({'show_id': model_class.set_show_id_by_id(instance.id)})
        kargs.update({'add_time': int(time.time())})
        kargs.update({'upd_time': int(time.time())})
    else:
        kargs.update({'upd_time': int(time.time())})
    model_class.update(**kargs).where(model_class.id == instance.id).execute()

